import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { showMessage } from './status'
import type { IResponse } from './type'
import { getToken, clearLocal } from '@/utils/auth'
import { endsWith, trimEnd } from 'lodash-es'

const baseUrl = import.meta.env.VITE_BASE_URL as string
const axiosInstance: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_APP_API_BASE_URL,
    timeout: 5000
})

// axios实例拦截请求
axiosInstance.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        const token = getToken()
        // console.log('token===', token)
        if (token) {
            if (config && config.headers) {
                config.headers['HTTP-X-TOKEN'] = token
            }
        }
        return config
    },
    (error: any) => {
        return Promise.reject(error)
    }
)

// axios实例拦截响应
axiosInstance.interceptors.response.use(
    (res: AxiosResponse) => {
        const { status, data } = res
        if (status === 200) {
            if (data instanceof Blob) {
                // console.log('res===', res);
                return res
            }
            const { code } = data
            if (code === 200 || code === 201) {
                return data.data ? data.data : data.code
            } else {
                switch (data.code) {
                    case 401:
                        showMessage('未授权，请重新登录(401)')
                        clearLocal()
                        window.location.href =
                            (endsWith(baseUrl, '/') ? trimEnd(baseUrl, '/') : baseUrl) + '/login'
                        break
                    case 500:
                        showMessage('内部服务调用失败')
                        // window.location.href = (endsWith(baseUrl, '/') ? trimEnd(baseUrl, '/') : baseUrl) + '/login'
                        // window.location.href = '/login'
                        // window.location.href = (endsWith(baseUrl, '/') ? trimEnd(baseUrl, '/') : baseUrl) + '/500'
                        break
                    default:
                        return data
                    // showMessage(data.msg)
                }
                return Promise.reject(data)
            }
        } else {
            showMessage('内部服务调用失败')
            window.location.href =
                (endsWith(baseUrl, '/') ? trimEnd(baseUrl, '/') : baseUrl) + '/500'
        }
    },
    // 请求失败
    (error: any) => {
        const { response } = error
        if (response) {
            // 请求已发出，但是不在2xx的范围
            showMessage(response.status)
            return Promise.reject(response.data)
        }
    }
)

const request = <T = any>(config: AxiosRequestConfig): Promise<T> => {
    const conf = config
    return new Promise((resolve) => {
        axiosInstance
            .request<any, AxiosResponse<IResponse>>(conf)
            .then((res: AxiosResponse<IResponse>) => {
                resolve(res as unknown as T)
            })
    })
}

export function get<T = any>(url: string, params?: any): Promise<T> {
    return request({
        url,
        params,
        method: 'GET'
    })
}

export function post<T = any>(url: string, data?: any): Promise<T> {
    return request({
        url,
        data,
        method: 'POST'
    })
}

export function put<T = any>(url: string, data?: any): Promise<T> {
    return request({
        url,
        data,
        method: 'PUT'
    })
}

export function $delete<T = any>(url: string): Promise<T> {
    return request({
        url,
        method: 'DELETE'
    })
}

export default request
export type { AxiosInstance, AxiosResponse }
